﻿CREATE PROCEDURE [audit].[StartBlackboxTrace]
@TraceID INT OUTPUT
AS
BEGIN
	DECLARE @RC int, @ERROR int
	SET @RC = 0
	SET @ERROR = 0

	IF(audit.IsTraceActive('Blackbox') = 1)
	BEGIN
		RAISERROR('The trace already exists.',0,1)
		SET @ERROR = @@ERROR
		GOTO ERROR_HANDLER
	END

	EXEC @RC = master.dbo.sp_trace_create @TraceID OUTPUT, 8 --BLACKBOX TRACE FLAG
	SET @ERROR = @@ERROR
	IF(@ERROR <> 0)
	OR(@RC <> 0)
		GOTO ERROR_HANDLER

	EXEC @RC = master.dbo.sp_trace_setstatus @TraceID, 1 --START TRACE FLAG
	SET @ERROR = @@ERROR
	IF(@ERROR <> 0)
	OR(@RC <> 0)
		GOTO ERROR_HANDLER

	GOTO EXIT_PROC

ERROR_HANDLER:
	IF(@RC <> 0)
		BEGIN
			DECLARE @ERROR_MESSAGE nvarchar(256)
			SET @ERROR_MESSAGE = audit.GetTraceReturnCodeValue(@RC)
			RAISERROR(@ERROR_MESSAGE, 16, 1)
		END
	ELSE
		SET @RC = @ERROR

	RAISERROR('Unable to start black box trace',16,1)

EXIT_PROC:
	RETURN(@RC)
END